﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Actya.Core.Infrastructure.Events
{
	public class EventPublisher : IEventPublisher
	{
		private readonly IEnumerable<Lazy<IEventListener>> _listeners;

		public EventPublisher(IEnumerable<Lazy<IEventListener>> listeners)
		{
			_listeners = listeners;
		}

		public void Publish<TPayload>(TPayload payload) where TPayload : class
		{
			var handlersForPayload = _listeners.Select(l => l.Value).OfType<IEventListener<TPayload>>();
			foreach (var handler in handlersForPayload)
			{
				handler.Handle(payload);
			}
		}
	}
}
